const Usecase = require('../../shared/usecase/Usecase')
const { UserNotFoundError } = require('../../domain/user/error')
const R = require('ramda')

class UpdateUser extends Usecase {
  constructor({ userRepo, database, currentUser }) {
    super(['UpdatedUser'])
    this.userRepo = userRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }
  async execute(data) {
    const { UpdatedUser } = this.eventMap
    const user = await this.userRepo.findById(data.id, {
      include: ['roleList'],
    })
    if (!user) throw new UserNotFoundError(data)
    const transaction = await this.sequelize.transaction()

    try {
      Object.assign(user, R.pick(['email', 'phone'], data))
      await user.validate()
      await this.userRepo.updateAndRoleList(user, data.roleIdList, {
        transaction,
        currentUser: this.currentUser,
      })
      await transaction.commit()
      this.emit(UpdatedUser, user)
    } catch (e) {
      await transaction.rollback()
      throw e
    }
  }
}

module.exports = UpdateUser
